const http = require('http');
const path = require('path');
const fs = require('fs');
const url = require('url');
let a = JSON.parse(fs.readFileSync(path.join(__dirname, 'persons.json'), 'utf-8'));
http.createServer((req, res) => {
    res.setHeader('content-type', 'text/html;charset=utf-8');
    if (req.url.startsWith('/login') && req.method == 'GET') {
        res.end(fs.readFileSync(path.join(__dirname, '/login.html')));
    }
    else if (req.url.startsWith('/register') && req.method == 'GET') {
        res.end(fs.readFileSync(path.join(__dirname, '/register.html')));
    }
    else if (req.url.startsWith("/dologin") && req.method == 'GET') {

        let user = url.parse(req.url, true).query;
        let tag = a.some(item => item.username == user.username && item.password == user.password);
        console.log(tag);
        if (tag) {
            res.end('登入成功');
        }
        else {
            res.end('账号密码错误');
        }
    }
    else if (req.url.startsWith("/doregister") && req.method == 'GET') {
        let user = url.parse(req.url, true).query;
        let tag = a.some(item => item.username == user.username);
        if (tag) {
            res.end('该账号已注册')
        }
        else {
            a.push(user);
            a = JSON.stringify(a);
            fs.writeFileSync(path.join(__dirname, 'persons.json'), a);
            res.end('注册成功')
        }
    }
    else {
        res.end('404');
    }
}).listen(3000, () => {
    console.log('服务器已开启');
});